package com.letoken.platform.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.letoken.platform.pub.annotation.auth.Permission;
import com.letoken.platform.pub.annotation.pub.Trim;
import com.letoken.platform.pub.constant.ConstantsValue;
import com.letoken.platform.pub.constant.LetokenUserConstant;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.req.PageData;
import com.letoken.platform.pub.res.ApiResponse;
import com.letoken.platform.pub.util.DataCalculationUtils;
import com.letoken.platform.pub.util.LocalDateTool;
import com.letoken.platform.pub.util.ReflexUtils;
import com.letoken.platform.repo.admin.req.mall.*;
import com.letoken.platform.repo.admin.res.mall.*;
import com.letoken.platform.repo.mall.dao.*;
import com.letoken.platform.repo.mall.po.*;
import com.letoken.platform.repo.utlis.PageDataUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/amb")
@Api(tags = "推广大使和星推官相关接口")
public class AdminAmbController {

    @Autowired
    AdminMallPromotionMapper adminMallPromotionMapper;
    @Autowired
    AdminMallAmbassadorMapper adminMallAmbassadorMapper;
    @Autowired
    AppMallAmbassadorRecordMapper appMallAmbassadorRecordMapper;
    @Autowired
    AdminMallIssueConfigMapper adminMallIssueConfigMapper;
    @Autowired
    AppMallAmbassadorReleaseMapper appMallAmbassadorReleaseMapper;


    @Permission(uri = "/amb/promotion/config",qx = "/configuration/identity")
    @Trim
    @GetMapping("/promotion/config")
    @ApiOperation(value = "星推官配置查询", notes = "星推官配置查询")
    public ApiResponse<AdminMallPromotion> getPromotionConfig() {
        LambdaQueryWrapper<AdminMallPromotion> lqwAmp = new LambdaQueryWrapper<>();
        lqwAmp.eq(AdminMallPromotion::getState,ConstantsValue.I_0)
                .orderByDesc(AdminMallPromotion::getId).last("limit 1")
                .select(AdminMallPromotion::getId,
                        AdminMallPromotion::getBonus,
                        AdminMallPromotion::getMinLevel,
                        AdminMallPromotion::getMaxLevel,
                        AdminMallPromotion::getMallLevel,
                        AdminMallPromotion::getMallNum,
                        AdminMallPromotion::getNeedPush);

        AdminMallPromotion a = adminMallPromotionMapper.selectOne(lqwAmp);
        a.setBonus(a.getBonus().multiply(new BigDecimal(100)));
        return ApiResponse.create(a);
    }


    @Permission(uri = "/amb/promotion/update",qx = "/promotion/config/update")
    @Trim
    @PostMapping("/promotion/update")
    @ApiOperation(value = "星推官配置修改", notes = "星推官配置修改")
    public ApiResponse updatePromotionConfig(@RequestBody PromotionUpdateReq req) {
        AdminMallPromotion amp = new AdminMallPromotion();
        Integer id = req.getId();
        req.setId(null);
        if (ReflexUtils.checkObjAllFieldsIsNull(req)){
            throw new ApiServiceException("至少修改一个值");
        }

        BeanUtils.copyProperties(req,amp);
        amp.setId(id);
        amp.setBonus(amp.getBonus().divide(BigDecimal.valueOf(100)));
        adminMallPromotionMapper.updateById(amp);

       return ApiResponse.create();
    }


    @Permission(uri = "/amb/config",qx = "/configuration/identity")
    @Trim
    @GetMapping("/config")
    @ApiOperation(value = "推广大使配置查询", notes = "推广大使配置查询")
    public ApiResponse<List<AdminMallAmbassador>> getAmbConfig() {
        LambdaQueryWrapper<AdminMallAmbassador> lqwAmp = new LambdaQueryWrapper<>();
        lqwAmp.eq(AdminMallAmbassador::getState,ConstantsValue.I_0).orderByAsc(AdminMallAmbassador::getLevel)
                .select(AdminMallAmbassador::getId,AdminMallAmbassador::getEco,AdminMallAmbassador::getBonus,AdminMallAmbassador::getLevel,AdminMallAmbassador::getLevelName);

        List<AdminMallAmbassador> list = adminMallAmbassadorMapper.selectList(lqwAmp);
        list.forEach(x->{
            x.setBonus(x.getBonus().multiply(BigDecimal.valueOf(100)));
        });

        return ApiResponse.create(list);
    }

    @Permission(uri = "/amb/updateConfig",qx = "/amb/updateConfig")
    @Trim
    @PostMapping("/updateConfig")
    @ApiOperation(value = "推广大使配置修改", notes = "推广大使配置修改")
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse updateConfig(@RequestBody List<AmbUpdateReq> reqs) {
        if (CollectionUtils.isEmpty(reqs)){
            throw new ApiServiceException("修改信息不能为空");
        }
        for (AmbUpdateReq r : reqs){
            if (ObjectUtils.isNotEmpty(r.getId()) && r.getId() > ConstantsValue.I_0){
                AdminMallAmbassador ama = new AdminMallAmbassador();
                ama.setId(r.getId());
                ama.setEco(r.getEco());
                ama.setBonus(r.getBonus());
                if (ObjectUtils.isNotEmpty(ama.getBonus()) || ObjectUtils.isNotEmpty(ama.getEco())){
                    if (ObjectUtils.isNotEmpty(ama.getBonus())){
                        ama.setBonus(ama.getBonus().divide(BigDecimal.valueOf(100)));
                    }
                    adminMallAmbassadorMapper.updateById(ama);
                }
            }
        }


        return ApiResponse.create();
    }



    @Permission(uri = "/amb/bonus/statistics",qx = "/amb/bonus/statistics")
    @Trim
    @GetMapping("/bonus/statistics")
    @ApiOperation(value = "推广大使分红统计数据", notes = "推广大使分红统计数据")
    public ApiResponse<AmbBonusStatisticsRes> bonusStatistics() {
        dayVo.isCurrentDay();
        AmbBonusStatisticsRes res = new AmbBonusStatisticsRes();
        res.setTodayBonus(appMallAmbassadorRecordMapper.statisticsData(dayVo.today,dayVo.tomorrow));
        res.setYesterdayBonus(appMallAmbassadorRecordMapper.statisticsData(dayVo.yesterday,dayVo.today));
        res.setMonthBonus(appMallAmbassadorRecordMapper.statisticsData(dayVo.monthStart, dayVo.tomorrow));
        res.setTotalBonus(appMallAmbassadorRecordMapper.statisticsData(dayVo.versionStart,dayVo.tomorrow));
        res.setWaitBonus(appMallAmbassadorRecordMapper.statisticsWaitCirculation());
        return ApiResponse.create(res);
    }





    @Permission(uri ="/amb/bonus/list" ,qx = "/ecology/ecologyRecord")
    @Trim
    @PostMapping("/bonus/list")
    @ApiOperation(value = "推广大使分红记录", notes = "推广大使分红记录")
    public ApiResponse<PageData<AmbListRes>> bonusList(@RequestBody @Validated AmbListReq req) {
        try {
            if (ObjectUtils.isNotEmpty(req.getLeId())){
                if (req.getLeId().startsWith(LetokenUserConstant.USER_ID_PREFIX)){
                    req.setUserId(Integer.valueOf(req.getLeId().replace(LetokenUserConstant.USER_ID_PREFIX,"")));
                }
            }
        } catch (NumberFormatException e) {
            log.error("leId格式不对",e);
        }

        LambdaQueryWrapper<AdminMallIssueConfig> lqwamic = new LambdaQueryWrapper<>();
        lqwamic.orderByDesc(AdminMallIssueConfig::getId).last("limit 1");
        AdminMallIssueConfig config = adminMallIssueConfigMapper.selectOne(lqwamic);

        Page<AmbListRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<AmbListRes> res = appMallAmbassadorRecordMapper.getAmbBonusRecord(page,req);
        if (CollectionUtils.isNotEmpty(res.getRecords())){
            res.getRecords().stream().forEach(x->{
                 x.setCycle(DataCalculationUtils.ambCalculationPeriod(null,x.getContributing(),config.getCirculationRate()));
            });
        }
        return ApiResponse.create(PageDataUtil.getPageData(res));
    }




    @Permission(uri = "/amb/bonus/releaseStatistics",qx = "/bonus/releaseStatistics")
    @Trim
    @GetMapping("/bonus/releaseStatistics")
    @ApiOperation(value = "推广大使流通统计数据", notes = "推广大使流通统计数据")
    public ApiResponse<AmbBonusReleaseRes> releaseStatistics() {
        dayVo.isCurrentDay();
        AmbBonusReleaseRes res = new AmbBonusReleaseRes();
        res.setYesterdayRelease(appMallAmbassadorReleaseMapper.statisticsReleaseData(dayVo.yesterday,dayVo.today));
        res.setTodayRelease(appMallAmbassadorReleaseMapper.statisticsReleaseData(dayVo.today,dayVo.tomorrow));
        res.setMonthRelease(appMallAmbassadorReleaseMapper.statisticsReleaseData(dayVo.monthStart, dayVo.tomorrow));
        res.setTotalRelease(appMallAmbassadorReleaseMapper.statisticsReleaseData(dayVo.versionStart,dayVo.tomorrow));
        return ApiResponse.create(res);
    }



    @Permission(uri = "/amb/bonus/releaseList",qx = "/ecology/ecologyFlow")
    @Trim
    @PostMapping("/bonus/releaseList")
    @ApiOperation(value = "推广大使流通记录", notes = "推广大使流通记录")
    public ApiResponse<PageData<AmbReleaseListRes>> bonusReleaseList(@RequestBody @Validated AmbReleaseListReq req) {
        try {
            if (ObjectUtils.isNotEmpty(req.getLeId())){
                if (req.getLeId().startsWith(LetokenUserConstant.USER_ID_PREFIX)){
                    req.setUserId(Integer.valueOf(req.getLeId().replace(LetokenUserConstant.USER_ID_PREFIX,"")));
                }
            }
        } catch (NumberFormatException e) {
            log.error("leId格式不对",e);
        }

        Page<AmbReleaseListRes> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        Page<AmbReleaseListRes> res = appMallAmbassadorReleaseMapper.getAmbReleaseRecord(page,req);
        return ApiResponse.create(PageDataUtil.getPageData(res));
    }






    private static DayVo dayVo = new DayVo();

    @Data
    static class DayVo{
        String now;
        String versionStart = "2023-01-01 00:00:00";
        String today;
        String yesterday;
        String tomorrow;
        String monthStart;

        private void isCurrentDay(){
            Date now = new Date();
            String currentTime = LocalDateTool.getDefaultTime(now,LocalDateTool.yyyyMMddHHmmss);
            if (StringUtils.isNotBlank(this.now) && this.now.equals(currentTime)){
                return ;
            }
            this.now = currentTime;
            this.today = LocalDateTool.getZeroPoint(now);
            this.yesterday = LocalDateTool.plusDay(now,-1);
            this.tomorrow = LocalDateTool.plusDay(now,1);
            this.monthStart = LocalDateTool.getNowByMonth(1);
        }


    }




}
